package com.huan.atm;

import com.google.gson.Gson;

import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class BankTask implements Runnable{
    private Socket socket;
    private Bank bank;
    private boolean flag;
    public BankTask(Socket socket,Bank bank){
        this.socket = socket;
        this.bank = bank;
        this.flag = true;
    }
    @Override
    public void run() {
        try (
                //需要将socket重新在try中注册，否则无法自动关闭
                Socket socket = this.socket;
                Scanner reader = new Scanner(socket.getInputStream());
                PrintWriter writer = new PrintWriter(socket.getOutputStream(),true);
                ){
            while (flag && !Thread.currentThread().isInterrupted()){
                //判断客户端是否传输数据，如果没有，则结束
                if (!reader.hasNext()){
                    System.out.println("客户端"+ socket.getRemoteSocketAddress()+"断开连接");
                    break;
                }
                //接受到消息，处理数据
                String command = reader.next();
                BankAccount account = null;
                JsonModel<BankAccount> jsonModel = new JsonModel();
                //判断用户指令
                if ("DEPOSIT".equals(command)){//存款
                    int id = reader.nextInt();
                    double money = reader.nextDouble();
                    account = bank.deposit(id, money);
                }else if ("WITHDRAW".equals(command)){//取款
                    int id = reader.nextInt();
                    double money = reader.nextDouble();
                    account = bank.withdraw(id, money);
                }else if ("BALANCE".equals(command)){//查看
                    int id = reader.nextInt();
                    account = bank.queryBalance(id);
                }else if ("QUIT".equals(command)){//退出
                    System.out.println("客户端"+ socket.getRemoteSocketAddress()+"断开连接");
                    break;
                }else{
                    jsonModel.setCode(0);
                    jsonModel.setErrorMsg("错误指令");
                    Gson gson = new Gson();
                    String json = gson.toJson(jsonModel);
                    writer.println(json);
                    writer.flush();
                }
                //将基本字符串改为json
                if (account!= null){
                    jsonModel.setCode(1);
                    jsonModel.setObj(account);
                    Gson gson = new Gson();
                    String json = gson.toJson(jsonModel);
                    writer.println(json);
                    writer.flush();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
